//
//  CaseViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "CaseViewController.h"
#import "CaseTableViewCell1.h"
#import "CaseTableViewCell2.h"
#import "CaseTableViewCell3.h"
#import "CaseTableViewCell4.h"
#import "PictureViewController.h"
#import "CaseCollectionViewCell1.h"
#import "WebViewController.h"
#import "CollectHandler.h"
#import "MainCol.h"
#import "MapViewController.h"
#import "MapTableViewCell.h"
@interface CaseViewController ()<UITableViewDataSource ,UITableViewDelegate,CaseTableViewCell3Deledate,CaseTableViewCell4Deledate,MBProgressHUDDelegate>{
    MBProgressHUD *HUD;
}
@property (nonatomic ,strong) UIView *view1;
@property (nonatomic ,strong) UITableView *tableview;
@property (nonatomic ,strong) NSMutableDictionary *dic;
@property (nonatomic ,strong) NSString *str2;
@property (nonatomic ,strong) UILabel *label;
@property (nonatomic ,strong) UIImage *image;

@end

@implementation CaseViewController
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    CollectHandler *collectHandler = [CollectHandler instandDefault];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MainCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name contains '%@'",self.titleCol]];
    NSArray *arr = [collectHandler.managedObjectContext executeFetchRequest:request error:nil];
    
    if (arr.count == 0) {
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    }else{
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor blueColor];
    }

    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightstyle"]) {
        self.view.backgroundColor = [UIColor colorWithRed:57/255.0 green:57/255.0 blue:57/255.0 alpha:1];
    }else{
        self.view.backgroundColor = [UIColor whiteColor];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
       self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"yishouchang.png"] style:UIBarButtonItemStyleDone target:self action:@selector(hand)];
    
    self.dic = [NSMutableDictionary dictionary];
    
    self.tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
     self.tableview.backgroundColor = [UIColor clearColor];
    self.tableview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 150)];
    [self.view addSubview:self.tableview];
    
    UIImageView *imageview = [[UIImageView alloc] init];
    imageview.frame = self.tableview.tableHeaderView.bounds;
    [self.tableview.tableHeaderView addSubview:imageview];
    [imageview sd_setImageWithURL:[NSURL URLWithString:_str1]];
    
    self.view1 = [[UIView alloc] init];
    [self.view addSubview:self.view1];
    self.view1.frame = self.view.bounds;
    self.view1.backgroundColor = [UIColor whiteColor];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
                
            case AFNetworkReachabilityStatusNotReachable:{
                
                NSLog(@"无网络");
                
                break;
                
            }
                
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                
                NSLog(@"WiFi网络");
                
                
                
                self.str2 = @"img_315_315";
                self.label = [[UILabel alloc] init];
                self.label.frame = CGRectMake(-250, Screenheight - 30, 250, 30);
                self.label.textAlignment = NSTextAlignmentCenter;
                self.label.backgroundColor = [UIColor whiteColor];
                self.label.text = @"Wifi网络为你加载高清图片";
                [self.view addSubview:self.label];
                break;
                
            }
                
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                
                NSLog(@"无线网络");
                self.str2 = @"img_210_210";
                
                
                break;
                
            }
                
            default:
                
                break;
        }
    }];
   
    
    [self handledata];
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"数据加载中...";
}
- (void)bbb
{
    MapViewController *map = [[MapViewController alloc] init];
    map.suit_address = [_dic objectForKey:@"suit_address"];
    map.ybj_position = [_dic objectForKey:@"ybj_position"];
    [self presentViewController:map animated:YES completion:^{
        
    }];
}


- (void)handledata
{
    NSString *str = [NSString stringWithFormat:@"http://www.meilele.com/mll_api/api/app_ybj2_detail?suit_id=%@",_str];
    
    NSLog(@"%@",str);
   [AFRequdstAndLoad dataURLStr:str datahand:^(id object) {
       

       self.dic = object;
       
       if (object) {
           [HUD hide:YES afterDelay:0];
           self.view1.hidden = YES;
           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               [UIView animateWithDuration:4 animations:^{
                   self.label.frame = CGRectMake(ScreenWidth + 50, Screenheight - 30, 250, 30);
               }];
 
              
           });
           

       }
        
        
        [_tableview reloadData];
    }];
    
    
}

- (void)hand
{
    CollectHandler *collectHandler = [CollectHandler instandDefault];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MainCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"name contains '%@'",self.titleCol]];
    NSArray *arr = [collectHandler.managedObjectContext executeFetchRequest:request error:nil];
    
    if (arr.count == 0) {
//        [self.button2 setTitle:@"取消收藏" forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor blueColor];
        MainCol *mainCol = [NSEntityDescription insertNewObjectForEntityForName:@"MainCol" inManagedObjectContext:collectHandler.managedObjectContext];
        mainCol.idNum = self.str;
        mainCol.name = self.titleCol;
        mainCol.pic = self.str1;
        [collectHandler saveContext];
//        NSLog(@"123");
//        self.menuV.hidden = YES;
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
    } else {
//        [self.button2 setTitle:@"收藏" forState:UIControlStateNormal];
//        self.menuV.hidden = YES;
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        self.image = [UIImage imageNamed:@"yishouchang.png"];
        MainCol *mainFetch = [arr lastObject];
        [collectHandler.managedObjectContext deleteObject:mainFetch];
        [collectHandler saveContext];
        
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"取消收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 40;
    }else if (indexPath.row == 1){
        NSString *str = [_dic objectForKey:@"design_text"];
        
        CGRect rect = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 75, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil];
        
        return rect.size.height + 1 + 20;
    }else if (indexPath.row == 2){
        NSString *str = [_dic objectForKey:@"expr_name"];
        
        CGRect rect = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 75, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil];
        
        return rect.size.height + 1 + 20;
    }else if (indexPath.row == 3){
        NSString *str = [_dic objectForKey:@"suit_address"];
        
        CGRect rect = [str boundingRectWithSize:CGSizeMake(ScreenWidth - 170, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil];
        
        return rect.size.height + 1 + 20;
    }else if (indexPath.row == 4){
         return 130;
    }else if (indexPath.row == 5){
        if ([[_dic objectForKey:@"goods_info"] count] == 0) {
            return 0;
        }else{
                return 130;
            }
        
    }
    return 0;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        CaseTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"case1"];
        if (cell == nil) {
            cell = [[CaseTableViewCell1 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"case1"];
            
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSString *str = [_dic objectForKey:@"designer_img"];
        NSString *str1 = [NSString stringWithFormat:@"http://image.meilele.com/%@",str];
        [cell.myimageview sd_setImageWithURL:[NSURL URLWithString:str1]];
        cell.mylabel1.text = [_dic objectForKey:@"designer"];
        return cell;
    } else {
        CaseTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"case"];
        if (cell == nil) {
            cell = [[CaseTableViewCell2 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"case"];
        }
        
        if (indexPath.row == 1) {
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.mylabel.text = @"设计理念 :";
            cell.mylabel1.text = [_dic objectForKey:@"design_text"];
            return cell;
            
        }else if (indexPath.row == 2){
             cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.mylabel.text = @"房间概况 :";
            cell.mylabel1.text =  [_dic objectForKey:@"expr_name"];
            return cell;
        }else if (indexPath.row == 3){
            MapTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"case23"];
            if (cell == nil) {
                cell = [[MapTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"case23"];
            }

            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.mylabel.text = @"小区地址 :";
            cell.mylabel1.text =  [_dic objectForKey:@"suit_address"];
            [cell.mybutton addTarget:self action:@selector(bbb) forControlEvents:UIControlEventTouchUpInside];
            return cell;

        }else if (indexPath.row == 4){
            
            CaseTableViewCell3 *cell = [tableView dequeueReusableCellWithIdentifier:@"case11"];
            if (cell == nil) {
                cell = [[CaseTableViewCell3 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"case11"];
            }
            cell.mylabel.text = @"更多照片 :";
            cell.imagesArr = [_dic objectForKey:self.str2];
            cell.name = [_dic objectForKey:@"expr_name"];
            cell.Deledate = self;
            return cell;
    
        }else if (indexPath.row == 5){
            CaseTableViewCell4 *cell = [tableView dequeueReusableCellWithIdentifier:@"case111"];
            if (cell == nil) {
                cell = [[CaseTableViewCell4 alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"case111"];
            }
            cell.mylabel.text = @"相关商品 :";
            cell.imagesArr1 =  [_dic objectForKey:@"goods_info"];
            
            cell.deledate = self;
           
            
            return cell;
        }
        
        
        
        return cell;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
  
    if (scrollView.contentOffset.y < - 140) {
        PictureViewController *pic = [[PictureViewController alloc] init];
        pic.picUrl = [_dic objectForKey:@"img_315_315"];
        pic.name = [_dic objectForKey:@"expr_name"];
//        [self.navigationController pushViewController:pic animated:YES];
        pic.modalTransitionStyle =  1;
        [self presentViewController:pic animated:YES completion:^{
            
        }];    }
}

- (void)passValue:(NSMutableArray *)idStr numer:(NSInteger)number
{
    
        NSString *str = [[idStr objectAtIndex:number] objectForKey:@"goods_url"];
        NSString *str1 = [NSString stringWithFormat:@"http://m.meilele.com%@",str];
        WebViewController *web = [[WebViewController alloc] init];
        web.str1 = str1;
        
        [self presentViewController:web animated:YES completion:^{
            
        }];
    
}
- (void)passValue1:(NSMutableArray *)ider number:(NSInteger)num name:(NSString *)name
{
    
    PictureViewController *pic = [[PictureViewController alloc] init];
    pic.picUrl = ider;
    pic.num = num;
    pic.name = name;

    pic.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//    [self.navigationController pushViewController:pic animated:YES];
    [self presentViewController:pic animated:YES completion:^{
        
    }];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
